import json
from flask_restful import Resource, reqparse

from app.models import Image as ImageDocument
from app.models import Instance as InstanceDocument
from app.resources.helpers import *

from flask import current_app as alog


class Instance(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('instanceId', type=str)

    def get(self):
        data = Instance.parser.parse_args()
        instance_id = data['instanceId']
        # first, find image name according to instance_id in Deployment
        # second, get image name, description, api path, description
        # third, return above params and instance_id
        return result_error('400', "请求错误") if not instance_id else \
            Instance.__get_instance_info(instance_id)

    @staticmethod
    def __get_instance_info(instance_id):
        try:
            image_name = InstanceDocument.objects(instance_id=instance_id)[0].service
        except Exception as e:
            return result_error("404", '数据库中无此镜像'), 404
        alog.logger.info(f'image_name: {image_name}')
        if not image_name:
            return result_error('404', '数据库中无此镜像'), 404
        image = ImageDocument.objects(name=image_name).exclude('id')[0]
        return result_success(json.loads(image.to_json()))
